package sudoku;

import java.util.Random;
import java.util.Vector;
import java.util.Iterator;

public class MakePuzzle
{
	private Vector<GridBox> vect = new Vector<GridBox>(82);
	
	private boolean isFull = false;
	
	private class GridBox// extends Constraint
	{
		private Vector<Integer> availableNum = new Vector<Integer>(9);
		private int downVectorID,
					acrossVectorID,
					regionVectorID;
		private int value;
		
		private GridBox()
		{
			for(int i = 1; i < 10; i++)
			{
				availableNum.add(i);
			}
		}
			
		boolean setValue()
		{
			Random rand = new Random();
			int nextVal;
			Constraint.checkConstraints(acrossVectorID, downVectorID, regionVectorID, availableNum);
			
			if(availableNum.size() == 0)
			{
				for(int i = 0; i < vect.size()-1; i++)
				{
					Constraint.checkConstraints(vect.get(i).acrossVectorID,
												vect.get(i).downVectorID,
												vect.get(i).regionVectorID,
												vect.get(i).availableNum);
				}
				return false;
			}
			else 
			{
				nextVal = availableNum.get(rand.nextInt(availableNum.size()));
				value = nextVal;
				
				Constraint.setConstraints(acrossVectorID, downVectorID, regionVectorID, value);
				return true;
			}
		}
		
		int setRegion(int x, int y)
		{
			return ((x/3)*3 + y/3);
		}
		
		void mapVectors(int num)
		{
			downVectorID = num % 9;
			acrossVectorID = num/9;
			regionVectorID = setRegion(acrossVectorID, downVectorID);
		}
	}
	
	public MakePuzzle()
	{
		
		while(!isFull)
		{
			vect.add(new GridBox());
			vect.lastElement().mapVectors(vect.size()-1);
			if(!vect.lastElement().setValue())
			{
				vect.remove(vect.lastElement());
				System.out.println("Before");
				for(int j = 0; j < vect.size()-1; j++)
				{
					if(j % 9 == 0) System.out.println();
					System.out.print(vect.get(j).value);
				}
				System.out.println();
				goBack();
				break;
			}
			
		}
		
	}
	
	void goBack()
	{
		//System.out.println("After");
		//int i = vect.size()-1;
		int k;
		//System.out.println(i);
		for(int i = 0; i < vect.size()-1; i++)
		{
			
			if(i % 9 == 0) System.out.println();
			System.out.print(vect.get(i).availableNum.size());
		}
		
		for(k = vect.size()-1; k > 0; k--)
		{
			if(vect.get(k).availableNum.size() > 0) break;
			//if(i % 9 == 0) System.out.println();
			//System.out.print(vect.get(i).availableNum.size());
		}
		
		System.out.println("After");
		//System.out.println(i);
		for(int j = 0; j < k; j++)
		{
			if(j % 9 == 0) System.out.println();
			System.out.print(vect.get(j).value);
		}
		
		
	}
	
}
